package com.ayuer.chapter08;

import java.util.Arrays;

public class SelectSortDemo {
    public static void main(String[] args) {
        int[] arr = {5, 4, 3, 2, 1};
//        selectSort(arr);
        selectSort2(arr);
        System.out.println(Arrays.toString(arr));
    }

    public static void selectSort(int[] arr) {
        //5, 4, 3, 2, 1
        //1.选择arr.length -1 次
        //2.选择交换索引的位置。初始a.length - 1，每次递减
        for (int right = arr.length - 1; right > 0; right--) {
            int max = right;
            for (int i = 0; i < right; i++) {
                if (arr[i] > arr[max]) {
                    max = i;
                }
            }
            //交换
            int tmp = arr[right];
            arr[right] = arr[max];
            arr[max] = tmp;
        }
    }

    public static void selectSort2(int[] arr) {
        //5, 4, 3, 2, 1
        //1.选择arr.length -1 次
        //2.选择交换索引的位置。初始a.length - 1，每次递减
        for (int i = 0; i < arr.length - 1; i++) {
            int max = arr.length - 1 - i;
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[max]) {
                    max = j;
                }
            }
            //交换
            int tmp = arr[arr.length - 1 - i];
            arr[arr.length - 1 - i] = arr[max];
            arr[max] = tmp;
        }
    }
}
